package top.superflow.version.db

import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}

import top.superflow.exception.RequestUnsupportedException
import top.superflow.version.compare.suggestion.Suggestion
import top.superflow.version.db.compare._

import scala.collection.mutable.{ListBuffer, Set}

trait IndexVersion extends Version{
  
  val name = new AtomicReference[String]
  
  val columnList = Set[String]()
  
  val unique = new AtomicBoolean(false)
  
  def getId : String = {
    this.name.get
  }
  
  def compare (targetStructure : Any): Option[Suggestion] = {
    
    targetStructure match {
      case dvp : Option[_] =>{
        if(dvp == None || dvp.isEmpty){
          Some(new MetadataConsistencySuggestion(new IndexIncompatibleColumnMissing(this, null), new MatchMissingAndExtraIndex(this, null)))
        }else{
          this.compare(dvp.get)
        }
      }
      
      case iv: IndexVersion => {
        val possibleSuggestionList = ListBuffer[Suggestion]()
        
        if(this.unique  !=  iv.unique){
          possibleSuggestionList += new MetadataConsistencySuggestion(new IndexIncompatibleColumnMissing(this, targetStructure), new MatchMissingAndExtraIndex(this, targetStructure))
        }
        
        possibleSuggestionList ++= compareColumnsToGetSuggestion(iv)
        
        summarizeSuggestion(possibleSuggestionList.toList)
      }
      
      case _ => {
        throw new RequestUnsupportedException(targetStructure)
      }
    }
  }
  
  private def compareColumnsToGetSuggestion(targetIndexVersion : IndexVersion) : List[Suggestion] = {
    val possibleSuggestionList = ListBuffer[Suggestion]()
    
    for(sourceColumn <- targetIndexVersion.columnList){
      if(!this.columnList.contains(sourceColumn)){
        possibleSuggestionList += new MetadataConsistencySuggestion(new IndexIncompatibleColumnMissing(this, targetIndexVersion), new AddMissingColumnOfIndex(this, targetIndexVersion))
      }
    }
    
    for(sourceColumn <- this.columnList){
      if(!targetIndexVersion.columnList.contains(sourceColumn)){
        possibleSuggestionList += new MetadataConsistencySuggestion(new IndexIncompatibleColumnExtra(this, targetIndexVersion), new RemoveExtraColumnOfIndex(this, targetIndexVersion))
      }
    }
    
    possibleSuggestionList.toList
  }
  
  def getMatchedChild (childDataVersionKey : Any) : Option[Version] = {
    childDataVersionKey match {
      case _ =>{
        None
      }
    }
  }
}